﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Furion.CMS.Application
{
    /// <summary>
    /// 事件监听器提供者
    /// </summary>
    public class OuterEventListenerProvider : IOuterEventProvider, IOuterEventListener
    {
        private ConcurrentQueue<OuterEventModel> deliveryQueue;
        private SemaphoreSlim signal;
        private readonly ListenerKey listenerKey;
        private readonly IOuterEventHub eventHub;

        public OuterEventListenerProvider(ListenerKey key, IOuterEventHub outerEventHub)
        {
            listenerKey = key;
            eventHub = outerEventHub;
        }

        public bool State { get; private set; }

        public void Dispose()
        {
            signal.Dispose();
            deliveryQueue.Clear();
            // 从集线器中移除
            eventHub.UnRegister(listenerKey.UserId, listenerKey.ChannelId);
        }

        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="notify"></param>
        public void Publish(OuterEventModel notify)
        {
            deliveryQueue?.Enqueue(notify);
            signal?.Release();
        }

        public void Start()
        {
            deliveryQueue = new ConcurrentQueue<OuterEventModel>();
            signal = new SemaphoreSlim(0, int.MaxValue);
            State = true;
        }

        public void Stop()
        {
            State = false;
        }

        public async Task<OuterEventModel> WaitTrigger(CancellationToken token = default)
        {
            await signal.WaitAsync(token);
            deliveryQueue.TryDequeue(out OuterEventModel body);
            return body;
        }
    }
}
